package com.cn.lotary.base.web;

import com.cn.lotary.base.dao.AbstractEntity;
import com.cn.lotary.base.dao.BaseDao;
import com.cn.lotary.util.LoggerUtils;
import com.cn.lotary.util.MessageBundle;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 *
 * @author Jason 11-Jul-2011
 */
public class BaseConverter<T extends AbstractEntity> implements Converter {

    private BaseDao<T> baseDao;

    public BaseConverter(BaseDao<T> baseDao) {
        this.baseDao = baseDao;
    }

    @Override
    public T getAsObject(FacesContext context, UIComponent component, String value) {
        //if (value == null || value.equals("") || !ObjectUtil.canConverterToInteger(value)) {
        if (value == null || value.equals("") || value.equals(MessageBundle.getLocalizedString("select"))) {
            return null;
        }
        
        return baseDao.find(value);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object object) {
        if (object == null || object.toString().equals("")) {
            return null;
        }
        T o = (T) object;
        try {
            Object id = o.getId();
            if (id != null) {
                return String.valueOf(id);
            }
        } catch (NullPointerException e) {
            LoggerUtils.error(e);
        } catch (ClassCastException e) {
            LoggerUtils.error(e);
        } catch (Exception e) {
            LoggerUtils.error(e);
        }
        return null;
    }
}
